package org.sky.sys.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.logging.log4j.Logger;
import org.sky.exception.ServiceException;
import org.sky.sys.entity.SysFile;
import org.sky.sys.mapper.SysFileMapper;
import org.sky.sys.mapper.SysCommonMapper;
import org.sky.sys.util.BspUtils;
import org.sky.sys.util.page.PageListData;
import org.sky.sys.util.page.PageListDataUtils;
import org.sky.util.LogUtils;
import org.sky.util.SnowflakeIdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.io.*;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

/**
* @author weifx
* @Title: SysFileService
* @ProjectName platform-core
* @Description: TODO{附件表业务类}
* @date 2019-3-17 17:23:14
* @Version 1.0
*/
@Service
public class SysFileService {
    private final static Logger log = LogUtils.getLogger(SysFileService.class);
    @Autowired
    private SysFileMapper sysFileMapper;
    @Autowired
    private SysCommonMapper sysCommonMapper;
    /**
    * 附件表分页查询
    * @param pageNum
    * @param pageSize
    * @param example
    * @return
    */
    public PageListData selectSysFileByPage(int pageNum, int pageSize, Example example){
        PageHelper.startPage(pageNum, pageSize);
        final PageInfo<SysFile> pageInfo = new PageInfo<SysFile>(sysFileMapper.selectByExample(example));
        return PageListDataUtils.getPageListData().setTotal(pageInfo.getTotal()).setRows(pageInfo.getList());
    }

    /**
     * 不分页查询
     * @param example
     * @return
     */
    public List<SysFile> selectSysFile(Example example){
        List<SysFile> list = sysFileMapper.selectByExample(example);
        return list;
    }
    /**
    * 保存{新增/修改}附件表
    * @param sysFile
    * @throws ServiceException
    */
    public void saveAddEditSysFile(SysFile sysFile) throws ServiceException{
        try {
            Timestamp ts = sysCommonMapper.queryTimestamp();
            if (null == sysFile.getId()) {
                Long id = SnowflakeIdWorker.getInstance().nextId();
                sysFile.setId(id);
                sysFile.setCreater(BspUtils.getLoginUser().getCode());
                sysFile.setCreateTime(ts);
                sysFile.setUpdater(BspUtils.getLoginUser().getCode());
                sysFile.setUpdateTime(ts);
                sysFileMapper.insertSelective(sysFile);
            } else {
                sysFile.setUpdater(BspUtils.getLoginUser().getCode());
                sysFile.setUpdateTime(ts);
                Example e = new Example(SysFile.class);
                e.createCriteria().andEqualTo("id", sysFile.getId());
                sysFileMapper.updateByExampleSelective(sysFile,e);
            }
        }catch (Exception e){
            e.printStackTrace();
            log.error("附件表保存失败:{}",e.getMessage());
            throw new ServiceException("附件表保存失败:"+e.getMessage(),e);
        }
    }
    /**
    * 根据ID删除附件表
    * @param list
    */
    public void delSysFileById(List<SysFile> list){
        try {
            List idList = new ArrayList();
            for (SysFile sysFile : list) {
                idList.add(sysFile.getId());
            }
            Example example = new Example(SysFile.class);
            example.createCriteria().andIn("id", idList);
            sysFileMapper.deleteByExample(example);
        }catch (Exception e){
            e.printStackTrace();
            log.error("附件表删除失败:{}",e.getMessage());
            throw new ServiceException("附件表删除失败:"+e.getMessage(),e);
        }
    }
    /**
    * 根据Id查询附件表
    * @param id
    * @return
    */
    public SysFile getSysFileById(Long id){
        Example example = new Example(SysFile.class);
        example.createCriteria().andEqualTo("id",id);
        return sysFileMapper.selectOneByExample(example);
    }

    /**
     * 插入保存附件
     * @param list
     */
    @Transactional
    public void batchInsert(List<SysFile> list){
        Timestamp ts = sysCommonMapper.queryTimestamp();
        for(SysFile sysFile:list) {
            Long id = SnowflakeIdWorker.getInstance().nextId();
            sysFile.setId(id);
            sysFile.setCreater(BspUtils.getLoginUser().getCode());
            sysFile.setCreateTime(ts);
            sysFile.setUpdater(BspUtils.getLoginUser().getCode());
            sysFile.setUpdateTime(ts);
            sysFileMapper.insertSelective(sysFile);
        }
    }

    /**
     * 获取图片附件的二进制
     * @param id
     * @return
     */
    public byte[] viewImage(Long id){
        Example example= new Example(SysFile.class);
        example.createCriteria().andEqualTo("id",id);
        SysFile sysFile = sysFileMapper.selectOneByExample(example);
        if(null == sysFile){
            throw new ServiceException("获取文件失败");
        }
        String filePath = sysFile.getPath();
        byte[] picture = getBytes(filePath);
        return picture;
    }

    /**
     * 获取图片二进制
     * @param bizType
     * @param bizCode
     * @return
     */
    public byte[] viewImage(String bizType,String bizCode){
        Example example= new Example(SysFile.class);
        example.createCriteria().andEqualTo("bizType",bizType)
        .andEqualTo("bizCode",bizCode);
        SysFile sysFile = sysFileMapper.selectOneByExample(example);
        if(null == sysFile){
            throw new ServiceException("获取文件失败");
        }
        String filePath = sysFile.getPath();
        byte[] picture = getBytes(filePath);
        return picture;
    }

    /**
     * 文件转二进制
     * @param filePath
     * @return
     */
    private byte[] getBytes(String filePath){
        byte[] buffer = null;
        try {
            File file = new File(filePath);
            FileInputStream fis = new FileInputStream(file);
            ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
            byte[] b = new byte[1000];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();
            buffer = bos.toByteArray();
        } catch (FileNotFoundException e) {
            log.error("文件转byte[]出错:{}",e.getMessage());
            e.printStackTrace();
        } catch (IOException e) {
            log.error("文件转byte[]出错:{}",e.getMessage());
            e.printStackTrace();
        }
        return buffer;
    }
}
